package com.wzw.springboot.principle.mvc.interceptors;

import com.wzw.springboot.principle.use.security.infrastructure.model.SecurityUser;
import com.wzw.springboot.principle.use.security.infrastructure.model.SecurityUserHolder;
import com.wzw.springboot.principle.use.security.manage.TokenManager;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截登录对象 SecurityUser 保存到ThreadLocal中
 *
 * @author Wangzhiwen
 */
@SuppressWarnings("all")
public class SecurityUserInterceptor implements AsyncHandlerInterceptor {

    private final TokenManager tokenManager;

    public SecurityUserInterceptor(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            SecurityUser securityUser = tokenManager.parse(request);
            SecurityUserHolder.set(securityUser);
        } catch (Exception e) {
            // ignored
        }
        AsyncHandlerInterceptor.super.afterConcurrentHandlingStarted(request, response, handler);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            SecurityUser securityUser = tokenManager.parse(request);
            SecurityUserHolder.set(securityUser);
        } catch (Exception e) {
            // ignored
        }
        return AsyncHandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityUserHolder.clean();
        AsyncHandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
